<?php
namespace app\admin\controller;
use think\Controller;
use think\Session;

class UploadController extends Controller {

	protected function _initialize() {
		parent::_initialize();
		if (!Session::has('ADMIN')) {
			$this->error('未登录');
		}
	}

	protected function oss_img($object, $path) {
		//去阿里云后台获取秘钥
		$config = config('aliyun');
		//实例化OSS
		try {
			$ossClient = new \OSS\OssClient($config['app_key'], $config['app_secret'], $config['endpoint']);
			//uploadFile的上传方法
			$ossClient->uploadFile($config['bucket'], $object, $path);
		} catch(\OSS\Core\OssException $e) {
			//如果出错这里返回报错信息
			return $e->getMessage();
		}
		//否则，完成上传操作
		return true;
	}

	/**
	 * 单图片上传
	 * $oss 是否上传到OSS
	 */
	public function upload($cate = 'temp') {
		$file = request()->file('file');
		$info = $file->move(ROOT_PATH . 'uploads');
		if ($info) {
			$src = '/' . str_replace('\\', '/', $info->getSaveName());
			if (config('aliyun_oss')) {
				// 上传到OSS
				$res = $this->oss_img($cate . '/' . date('Ymd') . '/' . $info->getFilename(), './uploads' . $src);
				if ($res) {
					$result = array(
						'code' => 1,
						'msg' => '上传成功',
						'src' => 'https://' . config('aliyun.bucket') . '.' . config('aliyun.endpoint') . '/' . $cate . $src
					);
				} else {
					$result = array(
						'code' => 0,
						'msg' => $res
					);
				}
			} else {
				if ($info) {
					$result = array(
						'code' => 1,
						'msg' => '上传成功',
						'src' => '/uploads' . $src
					);
				} else {
					$result = array(
						'code' => 0,
						'msg' => $file->getError()
					);
				}
			}
		} else {
			$result = array(
				'code' => 0,
				'msg' => $file->getError()
			);
		}
		return json($result);
	}

	/**
	 * 单图片上传
	 * $oss 是否上传到OSS
	 */
	public function editor($cate = 'temp') {
		$file = request()->file('file');
		$info = $file->move(ROOT_PATH . 'uploads');
		if ($info) {
			$src = '/' . str_replace('\\', '/', $info->getSaveName());
			if (config('aliyun_oss')) {
				// 上传到OSS
				$res = $this->oss_img($cate . '/' . date('Ymd') . '/' . $info->getFilename(), './uploads' . $src);
				if ($res) {
					$result = array(
						'code' => 1,
						'msg' => '上传成功',
						'src' => 'https://' . config('aliyun.bucket') . '.' . config('aliyun.endpoint') . '/' . $cate . $src
					);
				} else {
					$result = array(
						'code' => 0,
						'msg' => $res
					);
				}
			} else {
				if ($info) {
					$result = array(
						'code' => 1,
						'msg' => '上传成功',
						'data' => array(
							'src' => '/uploads' . $src,
							'title' => ''
						)
					);
				} else {
					$result = array(
						'code' => 0,
						'msg' => $file->getError()
					);
				}
			}
		} else {
			$result = array(
				'code' => 0,
				'msg' => $file->getError()
			);
		}
		return json($result);
	}

}
